/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.superduperbudget.central.ws.user;

import java.util.Date;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import se.superduperbudget.central.core.EMF;
import se.superduperbudget.central.db.SuperDuperUser;

/**
 * REST Web Service
 *
 * @author Emil
 */
@Path("/user/login")
public class Login {
    @Context
    private UriInfo context;

    /** Creates a new instance of Login */
    public Login() {
    }
    
    @GET
    @Produces("application/xml")
    public SuperDuperUser login() {
        MultivaluedMap<String, String> q = context.getQueryParameters();
        String user = q.get("username").get(0);
        String password = q.get("password").get(0);
        
        String query = "select u from SuperDuperUser u " + 
                "where u.username = :username and u.password = :password";
        
        EntityManager em = EMF.get().createEntityManager();
        TypedQuery<SuperDuperUser> tq = em.createQuery(query, SuperDuperUser.class);
        tq.setParameter("username", user);
        tq.setParameter("password", password);
        
        SuperDuperUser res = null;
        
        try {
            SuperDuperUser u = tq.getSingleResult();

            UUID uuid = UUID.randomUUID();
            u.setUuid(uuid.toString());
            u.setLoginCount(u.getLoginCount() + 1);
            u.setLastLogin(new Date());

            EntityTransaction tx = em.getTransaction();
            tx.begin();
            em.persist(u);
            tx.commit();
            
            res = u;
        } catch (NoResultException e) {}
        
        em.close();
        return res;
    }
}
